package com.sgb.kjwl.view.widget.house;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.R;
import com.sgb.jicai.entity.FilterEntity;
import com.sgb.kjwl.model.entity.user.PublicAttrEntity;
import com.sgb.link.utils.SizeUtils;
import com.sgb.kjwl.view.event.PickEvent;
import com.swgk.core.util.MLog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_DEVICE_ATTR;
import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_MACHINE_ATTR;

/**
 * 设备属性
 */
public class MachineAttrView extends FrameLayout {
    private final Context mContext;
    private MachineAttrAdapter mAdapter;
    private RecyclerView mRecycleView;

    private List<FilterEntity<List<FilterEntity>>> list;
    private List<FilterEntity> attrChildList;
    private List<PublicAttrEntity> mAttributesEntityList;
    //编辑时  选择时数据回显
    public SparseArray<String> mLastArray;
    private int type;
    private int selectPosition;
    private MachineAttrViewClickCallBack mCallBack;

    public void setAttrViewCallBack(MachineAttrViewClickCallBack mCallBack) {
        this.mCallBack = mCallBack;
    }

    public MachineAttrView(Context context) {
        this(context, null);
    }

    public MachineAttrView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MachineAttrView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        init();
    }

    private void init(){
        mLastArray = new SparseArray<>(20);
        mRecycleView = new RecyclerView(mContext);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mRecycleView.setLayoutParams(lp);
        this.addView(mRecycleView);
        mAdapter = new MachineAttrAdapter(mContext);
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecycleView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((position, val) -> {
            if (mCallBack != null){
                mCallBack.hideSoft();
            }
            //setSoftWareHide();
            if (!mAdapter.datas.get(position).isInput()) {
                attrChildList = mAdapter.datas.get(position).getChildren();
                selectPosition = 0;
                if (TextUtils.isEmpty(val)){
                    if (mLastArray.size() > 0) {
                        for (int i = 0; i < attrChildList.size(); i++) {
                            if (attrChildList.get(i).getStartVal().equals(mLastArray.get(position))) {
                                selectPosition = i;
                                break;
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < attrChildList.size(); i++) {
                        if (!TextUtils.isEmpty(val)){
                            if (attrChildList.get(i).getStartVal().equals(val)) {
                                selectPosition = i;
                                break;
                            }
                        }
                    }
                }
                showAttrPop(position);
            }
        });
        mAdapter.setFilterResultClick(datas -> {
            mAttributesEntityList = datas;
            if (type == EVENT_PUBLISH_MACHINE_ATTR) {
                EventBus.getDefault().post(PickEvent.make().setMessageTag(EVENT_PUBLISH_MACHINE_ATTR).setObject(mAttributesEntityList));
            } else {
                EventBus.getDefault().post(PickEvent.make().setMessageTag(EVENT_PUBLISH_DEVICE_ATTR).setObject(mAttributesEntityList));
            }
        });
    }

    public void setData(List<FilterEntity<List<FilterEntity>>> list, List<PublicAttrEntity> attributesEntityList){
        mAdapter.setData(list, attributesEntityList);
    }

    public interface MachineAttrViewClickCallBack{
        void hideSoft();
    }

    public List<PublicAttrEntity> getChooseAttr(){
        return mAdapter.attributesEntityList;
    }


    public  class MachineAttrAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        /***
         * 弹窗选择后返回的值
         */
        private String val = "";
        /***
         * 上下文
         */
        private final Context context;
        /***
         * 属性值 list
         */
        private final List<FilterEntity<List<FilterEntity>>> datas = new ArrayList<>();
        /***
         * 需要返回到上一个界面的实体
         */
        private PublicAttrEntity attributesEntity;
        /**
         * 返回到上一个界面的数据 list
         */
        private final List<PublicAttrEntity> attributesEntityList = new ArrayList<>();
        /**
         * 有数据时候，已经选择的数据
         */
        private final List<PublicAttrEntity> alreadyChoice = new ArrayList<>();
        /***
         * 确认按钮 type
         */
        //private int TYPE_FOOT = 1001;
        /**
         * 是否选择数据
         */
        private final boolean isNUll = false;
        /**
         * 是否第一次初始化adapter
         */
        private boolean iFirst;

        public MachineAttrAdapter(Context context){
            this.context = context;
        }

//        public MachineAttrAdapter(Context context, List<FilterEntity<List<FilterEntity>>> datas, List<PublicAttrEntity> mAlreadyChooce) {
//            this.context = context;
//            attributesEntityList.clear();
//            this.alreadyChoice.clear();
//            //this.alreadyChoice.addAll(mAlreadyChooce);
//            init(true, "", 0);
//        }

        public void setData(List<FilterEntity<List<FilterEntity>>> datas, List<PublicAttrEntity> mAlreadyChooce){
            this.datas.clear();
            if (datas != null) {
                this.datas.addAll(datas);
                notifyDataSetChanged();
            }
            //if (mAlreadyChooce != null && !mAlreadyChooce.isEmpty()) {
                this.alreadyChoice.clear();
            if (mAlreadyChooce != null && !mAlreadyChooce.isEmpty()) {
                this.alreadyChoice.addAll(mAlreadyChooce);
            }
            //}
            attributesEntityList.clear();
            MachineAttrView.this.mLastArray.clear();
            init(true, "", 0);
        }

        /***
         * 设置选择的值并刷新列表
         * @param content
         * @param item
         */
        public void setVal(String content, int item) {
            this.val = content;
            init(false, val, item);
            notifyItemChanged(item);
        }

        /***
         * 获取 非必要属性的值
         * @param content
         * @param item
         */
        public void getMyVal(String content, int item) {
            this.val = content;
            init(false, val, item);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            //if (viewType ==  TYPE_FOOT) {
                //View headerView = View.inflate(context, R.layout.item_ok_foot, null);
                //return new MachinePublishAttributeAdapter.FootViewHolder(headerView);
            //} else {
                View v = View.inflate(context, R.layout.item_machine_publish_attribute, null);
                return new MachineAttrAdapter.MyViewHolder(v);
            //}
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof MachineAttrAdapter.MyViewHolder) {
                if (datas.isEmpty()){
                    return;
                }
                if (datas.get(position).isInput()){
                    ((MachineAttrAdapter.MyViewHolder) holder).contentTv.setVisibility(View.GONE);
                    ((MachineAttrAdapter.MyViewHolder) holder).contentEdt.setVisibility(View.VISIBLE);
                    ((MachineAttrAdapter.MyViewHolder) holder).imageView.setVisibility(View.GONE);
                    ((MachineAttrAdapter.MyViewHolder) holder).contentEdt.setText("");
                } else {
                    ((MachineAttrAdapter.MyViewHolder) holder).contentTv.setVisibility(View.VISIBLE);
                    ((MachineAttrAdapter.MyViewHolder) holder).contentEdt.setVisibility(View.GONE);
                    ((MachineAttrAdapter.MyViewHolder) holder).imageView.setVisibility(View.VISIBLE);
                    ((MachineAttrAdapter.MyViewHolder) holder).contentTv.setText("");
                }
                if (datas.get(position).getAttrKey() == 0) {
                    ((MyViewHolder) holder).line.setVisibility(View.GONE);
                    ((MyViewHolder) holder).tvUnit.setVisibility(View.GONE);
                    ((MyViewHolder) holder).tvMust.setVisibility(View.GONE);
                } else {
                    ((MyViewHolder) holder).tvMust.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(datas.get(position).getUnit())){
                        ((MyViewHolder) holder).line.setVisibility(View.GONE);
                        ((MyViewHolder) holder).tvUnit.setVisibility(View.GONE);
                    } else {
                        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ((MyViewHolder) holder).tvUnit.getLayoutParams();
                        RelativeLayout.LayoutParams lpEt = (RelativeLayout.LayoutParams) ((MyViewHolder) holder).contentEdt.getLayoutParams();
                        if (datas.get(position).isInput()){
                            lp.rightMargin = SizeUtils.dp2px(15f);
                            lpEt.rightMargin = SizeUtils.dp2px(10f);
                            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                        } else {
                            lp.rightMargin = SizeUtils.dp2px(10f);
                            lpEt.rightMargin = SizeUtils.dp2px(15f);
                            lp.addRule(RelativeLayout.LEFT_OF, R.id.arrow_right_img);
                        }
                        ((MyViewHolder) holder).contentEdt.setLayoutParams(lpEt);
                        ((MyViewHolder) holder).tvUnit.setLayoutParams(lp);
                        ((MyViewHolder) holder).line.setVisibility(View.VISIBLE);
                        ((MyViewHolder) holder).tvUnit.setVisibility(View.VISIBLE);
                        ((MyViewHolder) holder).tvUnit.setText(datas.get(position).getUnit());
                    }
                }
                ((MachineAttrAdapter.MyViewHolder) holder).labelNameTv.setText(datas.get(position).getName());
                //重置数据
                if (iFirst) {
                    if (alreadyChoice != null && !alreadyChoice.isEmpty()) {
                        for (int i = 0; i < alreadyChoice.size(); i++) {
                            if (alreadyChoice.get(i).getAttributeNo() != null){
                                if (alreadyChoice.get(i).getAttributeNo().equals(datas.get(position).getAttributeNo())
                                   || alreadyChoice.get(i).getAttributeNo().equals(datas.get(position).getNo())) {
                                    attributesEntityList.add(alreadyChoice.get(i));
                                    MachineAttrView.this.mLastArray.put(position, alreadyChoice.get(i).getAttributeVal());
                                    if (!datas.get(position).isInput()) {
                                        ((MyViewHolder) holder).contentTv.setText(alreadyChoice.get(i).getAttributeVal());
                                    } else {
                                        ((MyViewHolder) holder).contentEdt.setText(alreadyChoice.get(i).getAttributeVal());
                                    }
                                }
                            }
                        }
                    }else{
                        getMyVal("", position);//解决初始状态下,无法获取列表所填写数据的bug
                    }
                } else if (!"".equals(val)) {
                    ((MachineAttrAdapter.MyViewHolder) holder).contentTv.setText(val);
                }
                if (mItemClickListener != null) {
                    ((MachineAttrAdapter.MyViewHolder) holder).rl.setOnClickListener(v -> mItemClickListener.onItemClick(position, ((MachineAttrAdapter.MyViewHolder) holder).contentTv.getText().toString()));
                }

                ((MachineAttrAdapter.MyViewHolder) holder).contentEdt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                        MLog.d("-----", charSequence.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        getMyVal(editable.toString(), position);
                    }
                });

            }
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        @Override
        public int getItemViewType(int position) {
//            在第一个位置添加头
//            if (position == datas.size()) {
//                return TYPE_FOOT;
//            }
            return super.getItemViewType(position);
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView contentTv;
            TextView labelNameTv;
            RelativeLayout rl;
            EditText contentEdt;
            ImageView imageView;
            TextView tvUnit;
            View line;
            TextView tvMust;

            public MyViewHolder(View itemView) {
                super(itemView);
                contentTv = itemView.findViewById(R.id.content_tv);
                labelNameTv = itemView.findViewById(R.id.label_name_tv);
                rl = itemView.findViewById(R.id.rl);
                contentEdt = itemView.findViewById(R.id.content_edt);
                imageView = itemView.findViewById(R.id.arrow_right_img);
                tvUnit = itemView.findViewById(R.id.unit_tv);
                line = itemView.findViewById(R.id.line_view);
                tvMust = itemView.findViewById(R.id.tvMust);
            }
        }


        //点击事件
        private ItemClickListener mItemClickListener;



        public void setOnItemClickListener(ItemClickListener itemClickListener) {
            this.mItemClickListener = itemClickListener;

        }

        /***
         * 初始化数据
         * @param iFirst 是否第一次初始化
         * @param val 选择的数据值
         * @param item 点击的位置
         */
        public void init(boolean iFirst, String val, int item) {
            this.iFirst = iFirst;
        /*if (iFirst && attributesEntityList == null) {

        } else*/
            if (!iFirst && attributesEntityList != null) {
                if (attributesEntityList.size() == 0) {
                    for (int i = 0; i < datas.size(); i++) {
                        attributesEntity = new PublicAttrEntity();
                        attributesEntity.setKey(datas.get(i).getAttrKey() + "");
                        attributesEntity.setAttributeNo(datas.get(i).getNo());
                        attributesEntity.setName(datas.get(i).getName());
                        attributesEntity.setUnit(datas.get(i).getUnit());
                        attributesEntityList.add(attributesEntity);

                    }
                }
                if (attributesEntityList.size() != 0 && item < attributesEntityList.size()) {
                    attributesEntityList.get(item).setAttributeVal(val);
                    attributesEntityList.get(item).setVal(val);
                }
            }
        }

        private FilterResultClick filterResultClick;



        public void setFilterResultClick(FilterResultClick filterResultClick) {
            this.filterResultClick = filterResultClick;
        }
    }


    //机械属性型号选择
    private void showAttrPop(int item) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (attrChildList.size() != 0) {
                    String content = attrChildList.get(options1).getStartVal();
                    mAdapter.setVal(content, item);
                    //map.put(item, options1);
                }
            }
        }).build();
        businessOption.setPicker(attrChildList);
        //if (map.get(item) == null) {
            businessOption.setSelectOptions(selectPosition);
//        } else {
//            businessOption.setSelectOptions((Integer) map.get(item));
//        }
        businessOption.show();
    }

    public interface ItemClickListener {
        void onItemClick(int position, String val);
    }

    public interface FilterResultClick {
        void result(List<PublicAttrEntity> attributesEntityList);
    }


}
